package org.jeecg.modules.rental.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.rental.entity.RentalBankCard;
import org.jeecg.modules.rental.entity.RentalWithdrawRecord;
import org.jeecg.modules.rental.req.WithdrawReq;
import org.jeecg.modules.rental.service.IRentalBankCardService;
import org.jeecg.modules.rental.service.IRentalWithdrawRecordService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 提现记录表
 * @Author: jeecg-boot
 * @Date:   2025-03-01
 * @Version: V1.0
 */
@Api(tags="提现记录表")
@RestController
@RequestMapping("/rental/rentalWithdrawRecord")
@Slf4j
public class RentalWithdrawRecordController extends JeecgController<RentalWithdrawRecord, IRentalWithdrawRecordService> {
	@Autowired
	private IRentalWithdrawRecordService rentalWithdrawRecordService;

	@Autowired
	private IRentalWithdrawRecordService withdrawRecordService;

	@Autowired
	private IRentalBankCardService rentalBankCardService;
	
	/**
	 * 分页列表查询
	 *
	 * @param rentalWithdrawRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "提现记录表-分页列表查询")
	@ApiOperation(value="提现记录表-分页列表查询", notes="提现记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<RentalWithdrawRecord>> queryPageList(RentalWithdrawRecord rentalWithdrawRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<RentalWithdrawRecord> queryWrapper = QueryGenerator.initQueryWrapper(rentalWithdrawRecord, req.getParameterMap());
		Page<RentalWithdrawRecord> page = new Page<RentalWithdrawRecord>(pageNo, pageSize);
		IPage<RentalWithdrawRecord> pageList = rentalWithdrawRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param rentalWithdrawRecord
	 * @return
	 */
	@AutoLog(value = "提现记录表-添加")
	@ApiOperation(value="提现记录表-添加", notes="提现记录表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_withdraw_record:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody RentalWithdrawRecord rentalWithdrawRecord) {
		rentalWithdrawRecordService.save(rentalWithdrawRecord);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param rentalWithdrawRecord
	 * @return
	 */
	@AutoLog(value = "提现记录表-编辑")
	@ApiOperation(value="提现记录表-编辑", notes="提现记录表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_withdraw_record:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody RentalWithdrawRecord rentalWithdrawRecord) {
		rentalWithdrawRecordService.updateById(rentalWithdrawRecord);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "提现记录表-通过id删除")
	@ApiOperation(value="提现记录表-通过id删除", notes="提现记录表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_withdraw_record:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		rentalWithdrawRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "提现记录表-批量删除")
	@ApiOperation(value="提现记录表-批量删除", notes="提现记录表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_withdraw_record:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.rentalWithdrawRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "提现记录表-通过id查询")
	@ApiOperation(value="提现记录表-通过id查询", notes="提现记录表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<RentalWithdrawRecord> queryById(@RequestParam(name="id",required=true) String id) {
		RentalWithdrawRecord rentalWithdrawRecord = rentalWithdrawRecordService.getById(id);
		if(rentalWithdrawRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(rentalWithdrawRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param rentalWithdrawRecord
    */
    //@RequiresPermissions("org.jeecg.modules.demo:rental_withdraw_record:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RentalWithdrawRecord rentalWithdrawRecord) {
        return super.exportXls(request, rentalWithdrawRecord, RentalWithdrawRecord.class, "提现记录表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("rental_withdraw_record:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RentalWithdrawRecord.class);
    }

	 @GetMapping("/listWithdraw")
	 public Result<IPage<RentalWithdrawRecord>> getWithdrawList(
			 @RequestParam(required = false) String bindCardId,
			 @RequestParam(required = false) String startDate,
			 @RequestParam(required = false) String endDate,
			 @RequestParam(required = false) String status,
			 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 try {
			 QueryWrapper<RentalWithdrawRecord> queryWrapper = new QueryWrapper<>();

			 // 添加银行卡ID条件
			 if (bindCardId != null && !bindCardId.isEmpty()) {
				 queryWrapper.eq("bank_card_id", bindCardId);
			 }

			 // 添加时间范围条件
			 if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
				 queryWrapper.between("apply_time", startDate, endDate);
			 }

			 // 添加状态条件
			 if (status != null && !status.isEmpty()) {
				 queryWrapper.eq("status", status);
			 }

			 // 按申请时间倒序排序
			 queryWrapper.orderByDesc("apply_time");

			 // 分页查询
			 Page<RentalWithdrawRecord> page = new Page<>(pageNo, pageSize);
			 IPage<RentalWithdrawRecord> pageList = withdrawRecordService.page(page, queryWrapper);

			 // 遍历结果，添加 bankCardName 字段
			 List<RentalWithdrawRecord> recordsWithBankCardName = pageList.getRecords().stream().map(record -> {
				 RentalBankCard bankCard = rentalBankCardService.getById(record.getBankCardId());
				 if (bankCard != null) {
					 // 拼接银行名称和卡号后4位
					 String cardCode = bankCard.getCardCode();
					 String bankCardName = bankCard.getBankCode() + (cardCode != null && cardCode.length() >= 4
							 ? cardCode.substring(cardCode.length() - 4)
							 : "");
					 record.setBankCardName(bankCardName);
				 } else {
					 // 如果没有找到银行卡信息，设置为空
					 record.setBankCardName("未知银行卡");
				 }
				 return record;
			 }).collect(Collectors.toList());

			 // 将处理后的记录重新设置到分页对象中
			 pageList.setRecords(recordsWithBankCardName);

			 return Result.OK(pageList);
		 } catch (Exception e) {
			 return Result.error("查询失败：" + e.getMessage());
		 }
	 }


	 @PostMapping("/apply")
	 public Result<String> applyWithdraw(
			 @RequestBody WithdrawReq withdrawRequestDTO) {

		 // 校验提现申请的参数有效性（手机号、验证码等逻辑可以根据实际业务实现）

		 RentalWithdrawRecord record = new RentalWithdrawRecord();
		 record.setBankCardId(withdrawRequestDTO.getBankcardId() );
		 record.setAmount(withdrawRequestDTO.getAmount());
		 record.setStatus("0"); // 默认状态为审核中
		 record.setApplyTime(new java.util.Date());

		 withdrawRecordService.save(record);
		 return Result.OK("提现申请提交成功！");
	 }


}
